package com.shao.utils.network;

import com.shao.exception.NetworkException;
import lombok.extern.slf4j.Slf4j;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/9 16:09
 */
@Slf4j
public class IpUtils {

    public static String getIpAddr() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                if (iface.isLoopback() || !iface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr instanceof Inet6Address || addr.isLoopbackAddress()) {
                        continue;
                    }
                    log.info("局域网IP地址：" + addr.getHostAddress());
                    return addr.getHostAddress();
                }
            }
            throw new NetworkException();
        } catch (SocketException e) {
            log.error("获取局域网ip地址发生异常：", e);
            throw new NetworkException(e);
        }
    }
}
